package com.bst.common.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class RedisTemplateConfig {

    @Autowired
    StringRedisTemplate redisTemplate;

    /*@Autowired(required = false)
    public void setRedisTemplate(StringRedisTemplate redisTemplate) {
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(stringSerializer);
        this.redisTemplate = redisTemplate;
    }*/

    public void putSet(Object[] data,String name) {
        SetOperations<String, String> vo = redisTemplate.opsForSet();
        String[] strArr = new String[data.length];
        for(int i=0;i<data.length;i++) {
            strArr[i] = data[i].toString();
        }
        if(vo.members(name)==null || vo.members(name).size()==0) {
            vo.add(name,strArr);
        } else {
            for(String str:strArr) {
                vo.union(name,str);
            }
        }
    }

    public Set<String> getSet(String name) {
        Set<String> set = redisTemplate.opsForSet().members(name);
        return set;
    }

    public void set(String key,String value) {
        redisTemplate.opsForValue().set(key,value);
    }

    public void set(String key,String value,Long time) {
        redisTemplate.opsForValue().set(key,value,time);
    }

    public String get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    public Boolean delete(String key) {
        return redisTemplate.delete(key);
    }

    public void expire(String key,long time) {
        redisTemplate.expire(key, time, TimeUnit.SECONDS);
    }

    public  boolean hasKey(String key){
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public List<String> multiGet(List<String> ids) {
        return redisTemplate.opsForValue().multiGet(ids);
    }
}
